package com.qike.yuandongguoji.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import com.qike.yuandongguoji.dto.*;
import com.qike.yuandongguoji.enums.*;
import com.qike.yuandongguoji.mapper.ApprovalMapper;
import com.qike.yuandongguoji.mapper.LeavingMapper;
import com.qike.yuandongguoji.mapper.OutReportMapper;
import com.qike.yuandongguoji.mapper.UserMapper;
import com.qike.yuandongguoji.pojo.*;
import com.qike.yuandongguoji.service.WeChatService;
import com.qike.yuandongguoji.tools.TimeTool;
import com.qike.yuandongguoji.vo.*;
import com.qiniu.util.UrlUtils;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.security.spec.AlgorithmParameterSpec;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @Author: Eric.zhou
 * @Date: 2019/6/3 14:38
 */
@Service
public class WeChatServiceImpl implements WeChatService {

    private RestTemplate httpRest = new RestTemplate();
    @Value("${wechat.appId}")
    private String appid;
    @Value("${wechat.secret}")
    private String secret;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OutReportMapper outReportMapper;
    @Autowired
    private LeavingMapper leavingMapper;
    @Autowired
    private ApprovalMapper approvalMapper;



    /**
     * 微信登录
     *
     * @param code
     * @return
     */
    @Override
    public LoginVo weChatLogin(String code) throws Exception {
//        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=wx709d3076ad5fe531&secret=f155a61f1c721f946e9711f94fe87118&js_code=" + code + "&grant_type=authorization_code";
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=wx388be925758be1d1&secret=9fb1dedb6f80736cab3d68324b3bb125&js_code=" + code + "&grant_type=authorization_code";
        ResponseEntity<String> forObject = httpRest.getForEntity(url, String.class);
//        LoginDto parse = (LoginDto) JSONObject.parse(forObject.getBody());
        LoginDto stu = (LoginDto) JSONObject.parseObject(forObject.getBody(), LoginDto.class);
        System.out.println("获取的id是"+stu.getUnionid());
//            if (stu.ge)
//        WeChatUser weChatUser = wechatUserMapper.selectByOpenId(stu.getOpenid());
//        if (weChatUser == null) {
//            WeChatUser wechatUser = new WeChatUser();
//            wechatUser.setAddTime(new Date());
//            wechatUser.setLoginTime(new Date());
//            wechatUser.setStatus(StatusEnums.YES.getEcode());
//            wechatUser.setMessageSwitch(StatusEnums.NO.getEcode());
//            wechatUser.setWechatSwitch(StatusEnums.YES.getEcode());
//            wechatUser.setOpenId(stu.getOpenid());
//            wechatUserMapper.insertSelective(wechatUser);
//        } else if (weChatUser.getStatus().equals(StatusEnums.NO.getEcode())) {
//            throw new Exception("账户已被冻结");
//        }
        UserExample userExample = new UserExample();
//        userExample.createCriteria().andOpenIdEqualTo()
//        userMapper.selectByExample()
        LoginVo vo = new LoginVo();
        vo.setRegister(Boolean.FALSE);
//        userMapper.selectByExample()
//        if (weChatUser.getCloum3()!=null&&weChatUser.getCloum4()!=null){
//            vo.setRegister(Boolean.TRUE);
//        }
        vo.setOpenId(stu.getOpenid());
        vo.setUnionid(stu.getUnionid());
        vo.setSessionKey(stu.getSession_key());


        return vo;
    }


    /**
     * 获取微信调用权限
     *
     * @return
     */
    public String getAccessToken() {
        String secret = "9fb1dedb6f80736cab3d68324b3bb125";
        //获取access_token
//        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
//                "&appid=" + appid + "&secret=" + secret;
//        String json = restTemplate.getForObject(url, String.class);
//        String accessToken = stringRedisTemplate.opsForValue().get("accessToken");
        AccessTokenDto forObject = httpRest.getForObject("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret, AccessTokenDto.class);
        return forObject.getAccess_token();
    }

    /**
     * 获取微信公众号调用权限
     *
     * @return
     */
    public String getOpenAccessToken() {
        String secret = "5cd3cd766b30ca33bcfa121a2b2231af";
        //获取access_token
//        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
//                "&appid=" + appid + "&secret=" + secret;
//        String json = restTemplate.getForObject(url, String.class);
//        String accessToken = stringRedisTemplate.opsForValue().get("accessToken");
        AccessTokenDto forObject = httpRest.getForObject("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + "wx1683a7429c32ada8" + "&secret=" + secret, AccessTokenDto.class);
        return forObject.getAccess_token();
    }









    public static String decrypt(byte[] key, byte[] iv, byte[] encData) throws Exception {
        AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        //解析解密后的字符串  
        return new String(cipher.doFinal(encData), "UTF-8");
    }


    public Object getPhoneNumber(PhoneNumberDto phoneNumberDto) throws Exception {
        // 被加密的数据
         byte[] dataByte = Base64.decode(phoneNumberDto.getEncryptedData());        // 加密秘钥
        byte[] keyByte = Base64.decode(phoneNumberDto.getSession_key());
        // 偏移量
        byte[] ivByte = Base64.decode(phoneNumberDto.getIv());
//        try {
            // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                JSONObject jsonObject = JSONObject.parseObject(result);
                String phoneNumber = (String) jsonObject.get("phoneNumber");
                UserExample example = new UserExample();
                example.createCriteria().andPhoneEqualTo(phoneNumber).andStatusEqualTo(StatusEnums.NO.getEcode());
                List<User> users = userMapper.selectByExample(example);
                if (users.size()>0){
                    User user = users.get(0);
                    user.setOpenId(phoneNumberDto.getOpenId());
//                    String openId = getOpenId(phoneNumberDto.getOpenId());
//                    user.setWxOpenId(openId);
                    user.setUnionid(phoneNumberDto.getUnionid());
                    String openId = getOpenId(phoneNumberDto.getOpenId());
                    System.out.println(phoneNumber+"获取到的wxopenid是:"+openId);
                    user.setWxOpenId(openId);
                    userMapper.updateByPrimaryKeySelective(user);
                }else {
                    throw new Exception("暂无登录权限 请联系管理员");
                }
                return JSONObject.parseObject(result);
            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        return null;
    }

    /**
     * 获取用户信息
     *
     * @param getUidDto
     * @return
     */
    @Override
    public GetUidVo getUid(GetUidDto getUidDto) {
        UserExample example = new UserExample();
        example.createCriteria().andPhoneEqualTo(getUidDto.getPhone()).andStatusEqualTo(StatusEnums.NO.getEcode());
        List<User> users = userMapper.selectByExample(example);
        if (users==null){
            return null;
        }else {
            User user = users.get(0);
            if (user.getOpenId()!=null){
                user.setOpenId(getUidDto.getOpenId());
                userMapper.updateByPrimaryKeySelective(user);
            }
            GetUidVo vo = new GetUidVo();
            vo.setName(user.getName());
            vo.setUid(user.getId());
            return vo;
        }

    }


    public String joinCode(String sencen, HttpServletRequest request) throws IOException {
        try {
            RestTemplate rest = new RestTemplate();
            InputStream inputStream = null;
            OutputStream outputStream = null;
            try {
                String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+getAccessToken();
                Map<String,Object> param = new HashMap<>();
                param.put("scene", sencen);
                param.put("page", "pages/index/index");
                param.put("width", 430);
//                param.put("auto_color", false);
//                Map<String,Object> line_color = new HashMap<>();
//                line_color.put("r", 0);
//                line_color.put("g", 0);
//                line_color.put("b", 0);
//                param.put("line_color", line_color);
               System.out.println("调用生成微信URL接口传参:" + param);
                MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
                HttpEntity requestEntity = new HttpEntity(param, headers);
                ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
               System.out.println("调用小程序生成微信永久小程序码URL接口返回结果:" + entity.getBody());
                byte[] result = entity.getBody();
               System.out.println(Base64.encode(result));
                inputStream = new ByteArrayInputStream(result);

                File file = new File("C:\\Users\\Admin\\Desktop\\"+sencen+".png");
                if (!file.exists()){
                    file.createNewFile();
                }
                outputStream = new FileOutputStream(file);
                int len = 0;
                byte[] buf = new byte[1024];
                while ((len = inputStream.read(buf, 0, 1024)) != -1) {
                    outputStream.write(buf, 0, len);
                }
                outputStream.flush();
            } catch (Exception e) {
//                LOG.error("调用小程序生成微信永久小程序码URL接口异常",e);
            } finally {
                if(inputStream != null){
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(outputStream != null){
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return null;    
        } catch (Exception e) {
            throw e;
        }
    }













    /**
     * 将二进制转换成文件保存
     * @param instreams 二进制流
     * @param imgPath 图片的保存路径
     * @param imgName 图片的名称
     * @return
     *      1：保存正常
     *      0：保存失败
     */
    public static int saveToImgByInputStream(InputStream instreams,String imgPath,String imgName){
        int stateInt = 1;
        if(instreams != null){
            try {
                File file=new File(imgPath,imgName);//可以是任何图片格式.jpg,.png等
                FileOutputStream fos=new FileOutputStream(file);
                byte[] b = new byte[1024];
                int nRead = 0;
                while ((nRead = instreams.read(b)) != -1) {
                    fos.write(b, 0, nRead);
                }
                fos.flush();
                fos.close();
            } catch (Exception e) {
                stateInt = 0;
                e.printStackTrace();
            } finally {
            }
        }
        return stateInt;
    }

//    /**
//     * 小程序接口
//     * @author 0200759
//     *
//     */
//    @Controller
//    @RequestMapping("/applet")
//    public class AppletController {


        /**
         * @param res
         * 调用二维码接口2(https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=ACCESS_TOKEN)
         */
//        @RequestMapping("/getQRCode")
        public void getQRCode(HttpServletResponse res, String sences) throws Exception {
            RestTemplate rest = new RestTemplate();
            InputStream inputStream = null;
            try {
//                AppletTokenResult appletTokenResult = CacheAppletUtil.get(Constants.APPLET_TOKEN);
//                if(appletTokenResult == null || StringUtil.isEmpty(appletTokenResult.getAccess_token())){
//                    throw new CommonException("小程序token获取失败！");
//                }
                String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="
                        +getAccessToken();
                Map<String, Object> param= new HashMap<String, Object>();
                param.put("scene", sences);
                param.put("path", "pages/index");
                param.put("width", 430);
                param.put("auto_color", false);
                Map<String,Object> line_color = new HashMap<>();
                line_color.put("r", 0);
                line_color.put("g", 0);
                line_color.put("b", 0);
                param.put("line_color", line_color);
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
//                HttpEntity<String> requestEntity = new HttpEntity<String>(new Gson().toJson(param), headers);
                HttpEntity<String> requestEntity = new HttpEntity<String>(JSON.toJSONString(param), headers);
                ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST,
                        requestEntity, byte[].class, new Object[0]);
                byte[] result = entity.getBody();
                inputStream = new ByteArrayInputStream(result);

                IOUtils.copy(inputStream, res.getOutputStream());

            } catch (Exception e) {
              throw  new Exception("调用小程序生成微信永久小程序码URL接口异常!");
            } finally {
                if(inputStream != null){
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }


    /**
     * 发送订阅消息sendTemplateMessage
     * 小程序订阅消息,发送服务通知
     *
     * @param openId     接收者（用户）的 openid
     * @param templateId 所需下发的模板消息的id
     * @param page       点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
     */
    public  void subscribeMessage(String openId, String templateId, String page, Map<String, TemplateData> map) {
//        String accessToken = GetTokenUtil.getAccessToken();
//        log.info("##accessToken:  " + accessToken);
        String accessToken = this.getAccessToken();
        SubscribeMessage subscribeMessage = new SubscribeMessage();
        //拼接数据
        subscribeMessage.setAccess_token(accessToken);
        subscribeMessage.setTouser(openId);
        subscribeMessage.setTemplate_id(templateId);
        subscribeMessage.setPage(page);
        subscribeMessage.setData(map);
        String json = JSONObject.toJSONString(subscribeMessage);
//        log.info("##订阅发送JSON数据请求:  " + json);
//        String ret = UrlUtils.sendPost(Wechat.SUBSCRIBEMESSAGE + accessToken, json);
        //如果不想找sendPost，可以借用Unirest 来发送 2选1 引的jar放在最下方了
        JsonNode ret = null;
      String url =  "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="+accessToken;
        try {
            ret = Unirest.post(url).body(json).asJson().getBody();
        } catch (UnirestException e) {
            e.printStackTrace();
        }

//        log.info("##订阅发送JSON数据返回:  " + ret);
        System.out.println(ret);
    }

    /**
     * 微信差旅行程
     *
     * @param getUidDto
     * @return
     */
    @Override
    public WechatOutListVo outList(OutListWeChatDto getUidDto) {
        WechatOutListVo vo = new WechatOutListVo();
        List<TodayList> todayLists = new ArrayList<>();
        List<TodayList> planLists= new ArrayList<>();
        List<TodayList> historyLists= new ArrayList<>();
        //查询当日行程
//        Date today = new Date();
        Date dayEnd = TimeTool.getDayEnd();
        Date dayStart = TimeTool.getDayBegin();
        OutReportExample example = new OutReportExample();
        example.createCriteria().andOrderStatusEqualTo(StatusEnums.NO.getEcode()).andUserIdEqualTo(getUidDto.getUid()).andOrModel(TimeTool.dateFormat(dayStart),TimeTool.dateFormat(dayEnd));
        example.setOrderByClause("out_time_end asc");
        List<OutReport> todayOut = outReportMapper.selectByExampleWithBLOBs(example);
        if (todayOut!=null&&todayOut.size()>0){
            for (OutReport outReport : todayOut) {
                TodayList todayList = new TodayList();
                todayList.setId(outReport.getId());
                todayList.setAddress(outReport.getAddress());
                todayList.setStartTime(TimeTool.dateFormatNoSS(outReport.getOutTimeStart()));
                todayList.setEndTime(TimeTool.dateFormatNoSS(outReport.getOutTimeEnd()));
                todayLists.add(todayList);
            }
        }
        //计划行程
        example.clear();
        example.createCriteria().andOutTimeStartGreaterThan(dayStart).andOrderStatusEqualTo(StatusEnums.NO.getEcode()).andUserIdEqualTo(getUidDto.getUid());
        example.setOrderByClause("out_time_end asc");
        List<OutReport> planOut = outReportMapper.selectByExampleWithBLOBs(example);
        if (planOut!=null&&planOut.size()>0){
            for (OutReport outReport : planOut) {
                TodayList todayList = new TodayList();
                todayList.setId(outReport.getId());
                todayList.setAddress(outReport.getAddress());
                todayList.setStartTime(TimeTool.dateFormatNoSS(outReport.getOutTimeStart()));
                todayList.setEndTime(TimeTool.dateFormatNoSS(outReport.getOutTimeEnd()));
                planLists.add(todayList);
            }
        }
        //历史行程
        example.clear();
        example.createCriteria().andOutTimeEndLessThan(dayEnd).andOrderStatusEqualTo(StatusEnums.NO.getEcode()).andUserIdEqualTo(getUidDto.getUid());
        example.setOrderByClause("out_time_end asc");
        Page page = PageHelper.startPage(getUidDto.getStartPage(), getUidDto.getPageSize());
        PageHelper.orderBy("add_time desc");
        List<OutReport> history = outReportMapper.selectByExampleWithBLOBs(example);
        if (history!=null&&history.size()>0){
            for (OutReport outReport : history) {
                TodayList todayList = new TodayList();
                todayList.setId(outReport.getId());
                todayList.setAddress(outReport.getAddress());
                todayList.setStartTime(TimeTool.dateFormatNoSS(outReport.getOutTimeStart()));
                todayList.setEndTime(TimeTool.dateFormatNoSS(outReport.getOutTimeEnd()));
                historyLists.add(todayList);
            }
        }
        vo.setTodayLists(todayLists);
        vo.setPlanLists(planLists);
        vo.setHistoryLists(historyLists);
        return vo;
    }

    /**
     * 发起请假审批
     *
     * @param addLeavingDto
     */
    @Override
    public void addLeaving(AddLeavingDto addLeavingDto) throws Exception {
        User user = userMapper.selectByPrimaryKey(addLeavingDto.getUid());
        Leaving leaving = new Leaving();
        leaving.setAddTime(new Date());
        leaving.setStatus(LeaveingStatusEnums.APPROVAL.getEcode());
        leaving.setStartTime(new Date(Long.parseLong(addLeavingDto.getStartTime())));
        leaving.setEndTime(new Date(Long.parseLong(addLeavingDto.getEndTime())));
        leaving.setRemark(addLeavingDto.getRemark());
        leaving.setType(addLeavingDto.getType());
        leaving.setTypeName(LeaveingOrderStatusEnums.statOf(addLeavingDto.getType()).getEmsg());
        leaving.setUserId(addLeavingDto.getUid());
        leaving.setUserName(user.getName());
        leavingMapper.insertSelective(leaving);
        User user1 = null;
        //todo 根据部门角色进行判断发起审批
        //判断是否需要二次审批
        //支援部门
        if (user.getDeptId().equals(5)) {
            Approval approval = new Approval();
            approval.setAuthorId(addLeavingDto.getUid());
            approval.setIsFinish(StatusEnums.NO.getEcode());
            approval.setFirstApprovalId(21);
            approval.setFirstApprovalStatus(0);
            approval.setOrderId(leaving.getId());
            approval.setType(0);
            approvalMapper.insertSelective(approval);
            user1 = userMapper.selectByPrimaryKey(21);

            //todo 通知审批人
        }
        //上海营业部
        if (user.getDeptId().equals(2)) {
            Approval approval = new Approval();
            approval.setAuthorId(addLeavingDto.getUid());
            approval.setIsFinish(StatusEnums.YES.getEcode());
            approval.setFirstApprovalStatus(0);
//            approval.setSecondApprovalStatus(0);

            if (user.getPositionId().equals(3)) {
                approval.setFirstApprovalId(21);
            }else {
//                approval.setFirstApprovalId(4);
                approval.setFirstApprovalId(21);
            }
//
//
//            if (user.getPositionId().equals(4)) {
//                approval.setFirstApprovalId(4);
//                approval.setSecondApprovalId(21);
//            } else if (user.getPositionId().equals(3)) {
//                approval.setFirstApprovalId(21);
//            }
            approval.setOrderId(leaving.getId());
            approval.setType(0);
            approvalMapper.insertSelective(approval);
            //todo 通知审批人
            user1 = userMapper.selectByPrimaryKey(21);
        }
        //服务部门
        if (user.getDeptId().equals(3)) {
            Approval approval = new Approval();
            approval.setAuthorId(addLeavingDto.getUid());
            approval.setIsFinish(StatusEnums.YES.getEcode());
            approval.setFirstApprovalStatus(0);

            if (user.getPositionId().equals(3)) {
                approval.setFirstApprovalId(21);
            }else {
                approval.setFirstApprovalId(21);
//                approval.setSecondApprovalId(21);
//                approval.setSecondApprovalStatus(0);
//                approval.setSecondApprovalStatus(0);
            }

//            if (user.getPositionId().equals(4)) {
//                approval.setFirstApprovalId(7);
//                approval.setSecondApprovalId(21);
//                approval.setSecondApprovalStatus(0);
//            } else if (user.getPositionId().equals(3)) {
//                approval.setFirstApprovalId(21);
//            }
            approval.setOrderId(leaving.getId());
            approval.setType(0);
            approvalMapper.insertSelective(approval);
            user1 = userMapper.selectByPrimaryKey(approval.getFirstApprovalId());
            //todo 通知审批人
        }
        //总务部门
        if (user.getDeptId().equals(4)) {
            Approval approval = new Approval();
            approval.setAuthorId(addLeavingDto.getUid());
            approval.setIsFinish(StatusEnums.YES.getEcode());
            approval.setFirstApprovalStatus(0);
                approval.setFirstApprovalId(21);
                approval.setOrderId(leaving.getId());
                approval.setType(0);
                approvalMapper.insertSelective(approval);
                //todo 通知审批人
                user1 = userMapper.selectByPrimaryKey(21);

        }
        //技术部门
        if (user.getDeptId().equals(28)) {
            Approval approval = new Approval();
            approval.setAuthorId(addLeavingDto.getUid());
            approval.setIsFinish(StatusEnums.YES.getEcode());
            approval.setFirstApprovalStatus(0);
            approval.setFirstApprovalId(21);
            approval.setOrderId(leaving.getId());
            approval.setType(0);
            approvalMapper.insertSelective(approval);
            //todo 通知审批人
            user1 = userMapper.selectByPrimaryKey(21);

        }
        ApprovalNoticeDto approvalNoticeDto = new ApprovalNoticeDto();
        approvalNoticeDto.setOpenId(user1.getWxOpenId());
        approvalNoticeDto.setName(user.getName());
        approvalNoticeDto.setRemark(leaving.getRemark());
        approvalNoticeDto.setType(LeaveingOrderStatusEnums.statOf(leaving.getType()).getEmsg());
        approvalNoticeDto.setTime(TimeTool.dateFormatNoSS(leaving.getStartTime())+"-"+TimeTool.dateFormat(leaving.getEndTime()));
        approvalNotice(approvalNoticeDto);

//        Map<String, TemplateData> map = new HashMap<>();
//        map.put("name1",new TemplateData(user.getName()));
//        map.put("thing2",new TemplateData(LeaveingOrderStatusEnums.statOf(leaving.getType()).getEmsg()));
//        map.put("thing3",new TemplateData(leaving.getRemark()));
//        map.put("date4",new TemplateData(TimeTool.dateFormat(leaving.getStartTime())));
//        map.put("date5",new TemplateData(TimeTool.dateFormat(leaving.getEndTime())));
//        subscribeMessage(user1.getOpenId(), "BoNk9CS5DDWiK65ffWjZ7KKhKgsR8yYxA9aWcySMERs", null,  map);
    }

    /**
     * 我发起的请假列表
     *
     * @param getUidDto
     * @return
     */
    @Override
    public MyLeavingListVo myLeavingList(OutListWeChatDto getUidDto) {
        MyLeavingListVo listVo = new MyLeavingListVo();
        LeavingExample example = new LeavingExample();
        example.createCriteria().andUserIdEqualTo(getUidDto.getUid());
        example.setOrderByClause("add_time desc");
        Page page = PageHelper.startPage(getUidDto.getStartPage(), getUidDto.getPageSize());
        PageHelper.orderBy("add_time desc");
        List<Leaving> leavings = leavingMapper.selectByExample(example);
        List<MyLeavingVo> list = new ArrayList<>();
        for (Leaving leaving : leavings) {
            MyLeavingVo vo = new MyLeavingVo();
            vo.setId(leaving.getId());
            vo.setName(leaving.getUserName());
            vo.setType(leaving.getType());
            vo.setTypeStr(leaving.getTypeName());
            vo.setStartTime(TimeTool.dateFormat(leaving.getStartTime()));
            vo.setEndTime(TimeTool.dateFormat(leaving.getEndTime()));
            vo.setOrderStatus(leaving.getStatus());
            vo.setRefuseRemark(leaving.getRefuseReason());
            vo.setRemark(leaving.getRemark());
            list.add(vo);
        }
        listVo.setList(list);
        listVo.setTotal(page.getTotal());
        return listVo;
    }

    /**
     * 待我审批列表
     *
     * @param getUidDto
     * @return
     */
    @Override
    public WaitMyLeavingListVo waitMyLeavingList(OutListWeChatDto getUidDto) {
        WaitMyLeavingListVo waitMyLeavingListVo = new WaitMyLeavingListVo();
        ApprovalExample example = new ApprovalExample();
        example.or().andFirstApprovalIdEqualTo(getUidDto.getUid()).andFirstApprovalStatusEqualTo(0);
        example.or().andSecondApprovalIdEqualTo(getUidDto.getUid()).andSecondApprovalStatusEqualTo(0).andFirstApprovalStatusEqualTo(1);
        Page page = PageHelper.startPage(getUidDto.getStartPage(), getUidDto.getPageSize());
        PageHelper.orderBy("is_finish  desc ");
        List<Approval> approvals = approvalMapper.selectByExample(example);
        List<MyLeavingVo> list = new ArrayList<>();
        for (Approval approval : approvals) {
            Leaving leaving = leavingMapper.selectByPrimaryKey(approval.getOrderId());
            MyLeavingVo vo = new MyLeavingVo();
            vo.setId(leaving.getId());
            vo.setName(leaving.getUserName());
            vo.setType(leaving.getType());
            vo.setTypeStr(leaving.getTypeName());
            vo.setStartTime(TimeTool.dateFormat(leaving.getStartTime()));
            vo.setEndTime(TimeTool.dateFormat(leaving.getEndTime()));
            vo.setOrderStatus(leaving.getStatus());
            vo.setRefuseRemark(leaving.getRefuseReason());
            vo.setRemark(leaving.getRemark());
            vo.setApprovalId(approval.getId());
            list.add(vo);
        }
        waitMyLeavingListVo.setList(list);
        waitMyLeavingListVo.setTotal(page.getTotal());
        return waitMyLeavingListVo;
    }

    /**
     * 审批
     *
     * @param approvalDto
     */
    @Override
    public void approval(ApprovalDto approvalDto) throws Exception {
        Boolean secondCall = false;
        Boolean firstCall = false;
        Boolean finish = false;
        Leaving leaving = null;
        User secondUser = null;
        Approval approval = approvalMapper.selectByPrimaryKey(approvalDto.getApprovalId());
        Integer secondApprovalId1 = approval.getSecondApprovalId();
        Integer firstApprovalId = approval.getFirstApprovalId();
        //第一审批人
        if (approvalDto.getUid().equals(firstApprovalId)){
            if (approvalDto.getAgree()){
                approval.setFirstApprovalStatus(1);
                if (approval.getSecondApprovalId()==null){
                    approval.setIsFinish(1);
                    leaving = leavingMapper.selectByPrimaryKey(approval.getOrderId());
                    leaving.setRefuseReason(approvalDto.getRefuseRemark());
                    leaving.setStatus(LeaveingStatusEnums.SUCCESS.getEcode());
                    leavingMapper.updateByPrimaryKeySelective(leaving);
                }else {
                    firstCall = true;
                }
            }else {
                finish = true;
                approval.setIsFinish(1);
                approval.setFirstApprovalStatus(2);
                leaving = leavingMapper.selectByPrimaryKey(approval.getOrderId());
                leaving.setStatus(LeaveingStatusEnums.REFUSE.getEcode());
                leaving.setRefuseReason(approvalDto.getRefuseRemark());
                leavingMapper.updateByPrimaryKeySelective(leaving);
            }
        }
        //第二审批人
        if (approvalDto.getUid().equals(secondApprovalId1)){
            if (approvalDto.getAgree()){
                approval.setSecondApprovalStatus(1);
                approval.setIsFinish(1);
                leaving = leavingMapper.selectByPrimaryKey(approval.getOrderId());
                leaving.setStatus(LeaveingStatusEnums.SUCCESS.getEcode());
                leavingMapper.updateByPrimaryKeySelective(leaving);
                secondCall = true;
                finish = true;
            }else {
                finish = true;
                approval.setIsFinish(1);
                approval.setSecondApprovalStatus(2);
                leaving = leavingMapper.selectByPrimaryKey(approval.getOrderId());
                leaving.setRefuseReason(approvalDto.getRefuseRemark());
                leaving.setStatus(LeaveingStatusEnums.REFUSE.getEcode());
                leavingMapper.updateByPrimaryKeySelective(leaving);
                secondCall = true;
            }
        }
            approvalMapper.updateByPrimaryKeySelective(approval);
            //todo 通知第二个审批人
        if (secondCall){
             secondUser = userMapper.selectByPrimaryKey(secondApprovalId1);
            ApprovalNoticeDto approvalNoticeDto = new ApprovalNoticeDto();
            approvalNoticeDto.setOpenId(secondUser.getOpenId());
            approvalNoticeDto.setName(leaving.getUserName());
            approvalNoticeDto.setRemark(leaving.getRemark());
            approvalNoticeDto.setType(LeaveingOrderStatusEnums.statOf(leaving.getType()).getEmsg());
            approvalNoticeDto.setTime(TimeTool.dateFormatNoSS(leaving.getStartTime())+"-"+TimeTool.dateFormat(leaving.getEndTime()));
            approvalNotice(approvalNoticeDto);
//            Map<String, TemplateData> map = new HashMap<>();
//            map.put("name1",new TemplateData(secondUser.getName()));
//            map.put("thing2",new TemplateData(LeaveingOrderStatusEnums.statOf(leaving.getType()).getEmsg()));
//            map.put("thing3",new TemplateData(leaving.getRemark()));
//            map.put("date4",new TemplateData(TimeTool.dateFormat(leaving.getStartTime())));
//            map.put("date5",new TemplateData(TimeTool.dateFormat(leaving.getEndTime())));
//            subscribeMessage(secondUser.getOpenId(), "BoNk9CS5DDWiK65ffWjZ7KKhKgsR8yYxA9aWcySMERs", null,  map);
        }

//        if (!flag&&)
        //todo 结果告知发起人
        if (finish) {
           User finishUser = userMapper.selectByPrimaryKey(approval.getAuthorId());
            ApprovalResultNoticeDto approvalNoticeDto = new ApprovalResultNoticeDto();
            if (approvalDto.getAgree()){
                approvalNoticeDto.setResult("同意");
//                map.put("phrase1",new TemplateData("同意"));
            }else {
                approvalNoticeDto.setResult("拒绝");
//                map.put("phrase1",new TemplateData("拒绝"));
            }

            approvalNoticeDto.setOpenId(finishUser.getWxOpenId());
            approvalNoticeDto.setName(leaving.getUserName());
            approvalNoticeDto.setTime(TimeTool.dateFormatNoSS(leaving.getStartTime())+"-"+TimeTool.dateFormat(leaving.getEndTime()));
            approvalResultNotice(approvalNoticeDto);
//            Map<String, TemplateData> map = new HashMap<>();

//            map.put("thing5",new TemplateData(LeaveingOrderStatusEnums.statOf(leaving.getType()).getEmsg()));
//            map.put("thing6",new TemplateData(leaving.getRemark()));
//            map.put("date3",new TemplateData(TimeTool.dateFormat(new Date())));
//            map.put("thing11",new TemplateData("无"));
//            subscribeMessage(secondUser.getOpenId(), "Hsp6pQM0W-CSTgcsyTLCyKbwzeoLc_oNITdqOPJ17yg", null,  map);
        }

    }

    /**
     * 发送差旅通知
     *
     * @param outNoticeDto
     */
    @Override
    public void outNotice(OutNoticeDto outNoticeDto) throws Exception {
        outNoticeDto.setOpenId(getOpenId(outNoticeDto.getOpenId()));
        String openId = "oTbcS5Wp-jcoV9Tx-FjXpeSUMta8";
            String token = this.getOpenAccessToken();
            String	regUser = "http://wxdemo.xxxx.com/wxdevices/bodycompositionmain?openId="+outNoticeDto.getOpenId();
            String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token;
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("touser", outNoticeDto.getOpenId()); //推送用户openid
            map.put("template_id", "Kliosf-2BiILQR2tMIuza1IKdc9SL5HYvSckQFTNOjc"); //指定模版ID
           map.put("appid", "wx388be925758be1d1"); //指定模版ID
            Map<String, Object> data_map =new HashMap<String, Object>();
            Map<String, Object> first = new HashMap<String, Object>();
            first.put("value", "外出通知目的地"+outNoticeDto.getAddress()+"车牌号"+outNoticeDto.getCarNo());
            first.put("color", "#000000");
            Map<String, Object> keynote1 = new HashMap<String, Object>();
            keynote1.put("value", outNoticeDto.getJoins());
            keynote1.put("color", "#000000");
            Map<String, Object> keynote2 = new HashMap<String, Object>();
            keynote2.put("value", outNoticeDto.getTime());
            keynote2.put("color", "#000000");
            Map<String, Object> remark = new HashMap<String, Object>();
            remark.put("value", outNoticeDto.getRemark());
            remark.put("color", "#000000");
            data_map.put("first", first);
            data_map.put("keyword1", keynote1);
            data_map.put("keyword2", keynote2);
            data_map.put("remark", remark);
            map.put("data", data_map);
//            JSONObject json = JSONObject.fromObject(map);
            String json = JSONObject.toJSONString(map);
//            String result = HttpUtil.sendPost(url, json.toString());
            JsonNode ret = null;
            ret = Unirest.post(url).body(json).asJson().getBody();
            System.out.println(ret);

    }

    /**
     * 发送用车通知
     *
     * @param carNoticeDto
     */
    @Override
    public void carNotice(CarNoticeDto carNoticeDto) throws Exception {
        if (carNoticeDto.getOpenId()==null){
            return;
        }
        carNoticeDto.setOpenId(getOpenId(carNoticeDto.getOpenId()));
        String token = this.getOpenAccessToken();
        String	regUser = "http://wxdemo.xxxx.com/wxdevices/bodycompositionmain?openId="+carNoticeDto.getOpenId();
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token;
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("touser", carNoticeDto.getOpenId()); //推送用户openid
        map.put("template_id", "zGcnx5-jbTCVYlc1QcmuWh7AkBUycK2i8rfvwGIw3NI"); //指定模版ID
       map.put("appid", "wx388be925758be1d1"); //指定模版ID
        map.put("miniprogram", "{\"appid\":\"wx388be925758be1d1\",\"pagepath\":\"index\"}"); //指定模版ID
        Map<String, Object> data_map =new HashMap<String, Object>();
        Map<String, Object> first = new HashMap<String, Object>();
        first.put("value", "用车通知车牌号"+carNoticeDto.getCarNo());
        first.put("color", "#000000");
        Map<String, Object> keynote1 = new HashMap<String, Object>();
        keynote1.put("value", carNoticeDto.getJoinNames());
        keynote1.put("color", "#000000");
        Map<String, Object> keynote2 = new HashMap<String, Object>();
        keynote2.put("value", carNoticeDto.getTime());
        keynote2.put("color", "#000000");
        Map<String, Object> keynote3 = new HashMap<String, Object>();
        keynote3.put("value", carNoticeDto.getAddress());
        keynote3.put("color", "#000000");
        Map<String, Object> remark = new HashMap<String, Object>();
        remark.put("value", carNoticeDto.getRemark());
        remark.put("color", "#000000");
        data_map.put("first", first);
        data_map.put("keyword1", keynote1);
        data_map.put("keyword2", keynote2);
        data_map.put("keyword3", keynote3);
        data_map.put("remark", remark);
        map.put("data", data_map);
//            JSONObject json = JSONObject.fromObject(map);
        String json = JSONObject.toJSONString(map);
//            String result = HttpUtil.sendPost(url, json.toString());
        JsonNode ret = null;
        ret = Unirest.post(url).body(json).asJson().getBody();
        System.out.println(ret);
    }

    /**
     * 参会通知
     *
     * @param joinMeetingDto
     */
    @Override
    public void joinMeeting(JoinMeetingDto joinMeetingDto) throws Exception {
        joinMeetingDto.setOpenId(getOpenId(joinMeetingDto.getOpenId()));
        String token = this.getOpenAccessToken();
        String	regUser = "http://wxdemo.xxxx.com/wxdevices/bodycompositionmain?openId="+joinMeetingDto.getOpenId();
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token;
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("touser", joinMeetingDto.getOpenId()); //推送用户openid
        map.put("template_id", "_kAoLBNYJv4GQA3L4K_4QY3SsPgDK-FsXfEA_lpdTSA"); //指定模版ID
       map.put("appid", "wx388be925758be1d1"); //指定模版ID
        Map<String, Object> data_map =new HashMap<String, Object>();
        Map<String, Object> first = new HashMap<String, Object>();
        first.put("value", "参会通知");
        first.put("color", "#000000");
        Map<String, Object> keynote1 = new HashMap<String, Object>();
        keynote1.put("value", joinMeetingDto.getJoinNames());
        keynote1.put("color", "#000000");
        Map<String, Object> keynote2 = new HashMap<String, Object>();
        keynote2.put("value", joinMeetingDto.getTopic());
        keynote2.put("color", "#000000");
        Map<String, Object> keynote3 = new HashMap<String, Object>();
        keynote3.put("value", joinMeetingDto.getTime());
        keynote3.put("color", "#000000");
        Map<String, Object> remark = new HashMap<String, Object>();
        remark.put("value", joinMeetingDto.getRemark());
        remark.put("color", "#000000");
        data_map.put("first", first);
        data_map.put("keyword1", keynote1);
        data_map.put("keyword2", keynote2);
        data_map.put("keyword3", keynote3);
        data_map.put("remark", remark);
        map.put("data", data_map);
//            JSONObject json = JSONObject.fromObject(map);
        String json = JSONObject.toJSONString(map);
//            String result = HttpUtil.sendPost(url, json.toString());
        JsonNode ret = null;
        ret = Unirest.post(url).body(json).asJson().getBody();
        System.out.println(ret);
    }

    /**
     * 会议取消通知
     *
     * @param joinMeetingDto
     */
    @Override
    public void cancelMeeting(JoinMeetingDto joinMeetingDto) throws Exception {
//        joinMeetingDto.setOpenId(getOpenId(joinMeetingDto.getOpenId()));
        String token = this.getOpenAccessToken();
        String	regUser = "http://wxdemo.xxxx.com/wxdevices/bodycompositionmain?openId="+joinMeetingDto.getOpenId();
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token;
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("touser", joinMeetingDto.getOpenId()); //推送用户openid
        map.put("template_id", "OzNKGTxUgNzG-soDaE2ZgDh2d0MdYGEYX1ntfgTRuXM"); //指定模版ID
       map.put("appid", "wx388be925758be1d1"); //指定模版ID
        Map<String, Object> data_map =new HashMap<String, Object>();
        Map<String, Object> first = new HashMap<String, Object>();
        first.put("value", "会议取消通知");
        first.put("color", "#000000");
        Map<String, Object> keynote1 = new HashMap<String, Object>();
        keynote1.put("value", joinMeetingDto.getTopic());
        keynote1.put("color", "#000000");
        Map<String, Object> keynote2 = new HashMap<String, Object>();
        keynote2.put("value", joinMeetingDto.getTime());
        keynote2.put("color", "#000000");
        Map<String, Object> keynote3 = new HashMap<String, Object>();
        keynote3.put("value", joinMeetingDto.getTime());
        keynote3.put("color", "#000000");
        Map<String, Object> remark = new HashMap<String, Object>();
        remark.put("value", "您有会议计划已取消，请留意");
        remark.put("color", "#000000");
        data_map.put("first", first);
        data_map.put("keyword1", keynote1);
        data_map.put("keyword2", keynote2);
        data_map.put("keyword3", keynote3);
        data_map.put("remark", remark);
        map.put("data", data_map);
//            JSONObject json = JSONObject.fromObject(map);
        String json = JSONObject.toJSONString(map);
//            String result = HttpUtil.sendPost(url, json.toString());
        JsonNode ret = null;
        ret = Unirest.post(url).body(json).asJson().getBody();
        System.out.println(ret);
    }



    /**
     * 审批通知
     *
     * @param approvalNoticeDto
     */
    @Override
    public void approvalNotice(ApprovalNoticeDto approvalNoticeDto) throws Exception {
//        approvalNoticeDto.setOpenId(getOpenId(approvalNoticeDto.getOpenId()));
        String token = this.getOpenAccessToken();
        String	regUser = "http://wxdemo.xxxx.com/wxdevices/bodycompositionmain?openId="+approvalNoticeDto.getOpenId();
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token;
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("touser", approvalNoticeDto.getOpenId()); //推送用户openid
        map.put("template_id", "thi045rO17rbKvfhR2_5d1ZhZM0Wdm1vlKLuv2BnhTM"); //指定模版ID
       map.put("appid", "wx388be925758be1d1"); //指定模版ID
        Map<String, Object> data_map =new HashMap<String, Object>();
        Map<String, Object> first = new HashMap<String, Object>();
        first.put("value", "你有新的审批通知");
        first.put("color", "#000000");
        Map<String, Object> keynote1 = new HashMap<String, Object>();
        keynote1.put("value", approvalNoticeDto.getName());
        keynote1.put("color", "#000000");
        Map<String, Object> keynote2 = new HashMap<String, Object>();
        keynote2.put("value", approvalNoticeDto.getType());
        keynote2.put("color", "#000000");
        Map<String, Object> keynote3 = new HashMap<String, Object>();
        keynote3.put("value", approvalNoticeDto.getTime());
        keynote3.put("color", "#000000");
        Map<String, Object> remark = new HashMap<String, Object>();
        remark.put("value", approvalNoticeDto.getRemark());
        remark.put("color", "#000000");
        data_map.put("first", first);
        data_map.put("keyword1", keynote1);
        data_map.put("keyword2", keynote2);
        data_map.put("keyword3", keynote3);
        data_map.put("remark", remark);
        map.put("data", data_map);
//            JSONObject json = JSONObject.fromObject(map);
        String json = JSONObject.toJSONString(map);
//            String result = HttpUtil.sendPost(url, json.toString());
        JsonNode ret = null;
        ret = Unirest.post(url).body(json).asJson().getBody();
        System.out.println(ret);
    }


    /**
     * 获取所有微信公众号openid
     * @param unitId
     * @return
     */
    public String getOpenId(String openId) throws Exception {
        System.out.println("获取公众号:"+openId);
        if (StringUtils.isEmpty(openId)){
            return null;
        }
        UserExample userExample = new UserExample();
        userExample.createCriteria().andOpenIdEqualTo(openId);
        List<User> users = userMapper.selectByExample(userExample);
        if (users.size()<=0){
            return null;
        }
        User user = users.get(0);
        if (user.getWxOpenId()!=null){
            return user.getWxOpenId();
        }
        String token = this.getOpenAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=+"+token+"&next_openid=";
        String openUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=+"+token+"&openid=";
        RestTemplate restTemplate = new RestTemplate();
        JsonRootBean forObject = restTemplate.getForObject(url, JsonRootBean.class);
        List<String> openid = forObject.getData().getOpenid();
        for (String s : openid) {
            RestTemplate restTemplate1 = new RestTemplate();
            WxInfo forObject1 = restTemplate1.getForObject(openUrl + s, WxInfo.class);
            System.out.println(forObject1.getUnionid());
            System.out.println(user.getUnionid());
            if (forObject1.getUnionid().equals(user.getUnionid())){
                user.setWxOpenId(forObject1.getOpenid());
                userMapper.updateByPrimaryKeySelective(user);
                return forObject1.getOpenid();
            }
        }
        return null;

    }

    /**
     * 审批结果通知
     *
     * @param approvalNoticeDto
     */
    @Override
    public void approvalResultNotice(ApprovalResultNoticeDto approvalNoticeDto) throws Exception {
        approvalNoticeDto.setOpenId(getOpenId(approvalNoticeDto.getOpenId()));
        String token = this.getOpenAccessToken();
        String	regUser = "http://wxdemo.xxxx.com/wxdevices/bodycompositionmain?openId="+approvalNoticeDto.getOpenId();
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token;
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("touser", approvalNoticeDto.getOpenId()); //推送用户openid
        map.put("template_id", "MKIFPm7kXDYawEYBJRAM8x9VIdYvvns3O9XT1kRnPP8"); //指定模版ID
        map.put("appid", "wx388be925758be1d1"); //指定模版ID
        map.put("miniprogram", "{\"appid\":\"wx388be925758be1d1\",\"pagepath\":\"index\"}"); //指定模版ID
//       map.put("appid", "wx388be925758be1d1"); //指定模版ID
        Map<String, Object> data_map =new HashMap<String, Object>();
        Map<String, Object> first = new HashMap<String, Object>();
        first.put("value", "您的审批已完成");
        first.put("color", "#000000");
        Map<String, Object> keynote1 = new HashMap<String, Object>();
        keynote1.put("value", approvalNoticeDto.getTime());
        keynote1.put("color", "#000000");
        Map<String, Object> keynote2 = new HashMap<String, Object>();
        keynote2.put("value", approvalNoticeDto.getResult());
        keynote2.put("color", "#000000");
        Map<String, Object> remark = new HashMap<String, Object>();
        remark.put("value", "请妥善处理假期间的工作");
        remark.put("color", "#000000");
        data_map.put("first", first);
        data_map.put("keyword1", keynote1);
        data_map.put("keyword2", keynote2);
        data_map.put("remark", remark);
        map.put("data", data_map);
//            JSONObject json = JSONObject.fromObject(map);
        String json = JSONObject.toJSONString(map);
//            String result = HttpUtil.sendPost(url, json.toString());
        JsonNode ret = null;
        ret = Unirest.post(url).body(json).asJson().getBody();
        System.out.println(ret);
    }

    /**
     * 请假撤回
     *
     * @param delLeavingDto
     */
    @Override
    @Transactional
    public void delLeaving(DelLeavingDto delLeavingDto) {
        Leaving leaving = leavingMapper.selectByPrimaryKey(delLeavingDto.getId());
        leaving.setStatus(StatusEnums.YES.getEcode());
        leavingMapper.deleteByPrimaryKey(leaving.getId());
        //删除审批
        ApprovalExample example = new ApprovalExample();
        example.createCriteria().andOrderIdEqualTo(leaving.getId());
        List<Approval> approvals = approvalMapper.selectByExample(example);
        if (approvals.size()>0){
            Approval approval = approvals.get(0);
            approvalMapper.deleteByPrimaryKey(approval.getId());
        }
    }

    /**
     * 获取用户状态
     *
     * @param getUidDto
     * @return
     */
    @Override
    public Boolean getUserStatus(GetUidDto getUidDto) {
        UserExample example = new UserExample();
        example.createCriteria().andPhoneEqualTo(getUidDto.getPhone()).andStatusEqualTo(StatusEnums.NO.getEcode());
        List<User> users = userMapper.selectByExample(example);
        if (users==null|| users.size()<=0){
            return false;
        }else {
            return true;
        }
    }

    @Override
    public void testNotice() {

    }

    /**
     * 体脂数据推送信息给微信
     * @param access_token
     * @param open_id
     */
    public  void sendBodyCompostionInfoToWeChart(final String access_token,final String open_id,final String user_name,final String bodyCompostionText,final String test_time){

        try {
            String token = this.getOpenAccessToken();
            String openId = "oTbcS5Wp-jcoV9Tx-FjXpeSUMta8";
            String	regUser = "http://wxdemo.xxxx.com/wxdevices/bodycompositionmain?openId="+openId;
            String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token;
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("touser", openId); //推送用户openid
            map.put("template_id", "Kliosf-2BiILQR2tMIuza1IKdc9SL5HYvSckQFTNOjc"); //指定模版ID
           map.put("appid", "wx388be925758be1d1"); //指定模版ID
            Map<String, Object> data_map =new HashMap<String, Object>();
            Map<String, Object> first = new HashMap<String, Object>();
            first.put("value", "您好，你有一条体脂检测信息");
            first.put("color", "#000000");
            Map<String, Object> keynote1 = new HashMap<String, Object>();
            keynote1.put("value", "咯阿里");
            keynote1.put("color", "#000000");
            Map<String, Object> keynote2 = new HashMap<String, Object>();
            keynote2.put("value", "2020年8月-9月");
            keynote2.put("color", "#000000");
            Map<String, Object> remark = new HashMap<String, Object>();
            remark.put("value", "备注123");
            remark.put("color", "#000000");
            data_map.put("first", first);
            data_map.put("keyword1", keynote1);
            data_map.put("keyword2", keynote2);
            data_map.put("remark", remark);
            map.put("data", data_map);
//            JSONObject json = JSONObject.fromObject(map);
            String json = JSONObject.toJSONString(map);
//            String result = HttpUtil.sendPost(url, json.toString());
            JsonNode ret = null;
            ret = Unirest.post(url).body(json).asJson().getBody();
            System.out.println(ret);
//            JSONObject json_arr = JSONObject.fromObject(result);
//            String isOk = String.valueOf(json_arr.get("errmsg"));
        } catch (Exception e) {
        }

    }

    public static void main(String[] args) throws UnirestException {
        WeChatServiceImpl weChatService = new WeChatServiceImpl();

        String openId = "oC7ZW5sZRfa9dGTj1z5oBOtZk65M";
        String token = weChatService.getOpenAccessToken();
        String	regUser = "http://wxdemo.xxxx.com/wxdevices/bodycompositionmain?openId="+openId;
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token;
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("touser", openId); //推送用户openid
        map.put("template_id", "thi045rO17rbKvfhR2_5d1ZhZM0Wdm1vlKLuv2BnhTM"); //指定模版ID
        map.put("appid", "wx388be925758be1d1"); //指定模版ID
        Map<String, Object> data_map =new HashMap<String, Object>();
        Map<String, Object> first = new HashMap<String, Object>();
        first.put("value", "你有新的审批通知");
        first.put("color", "#000000");
        Map<String, Object> keynote1 = new HashMap<String, Object>();
        keynote1.put("value", "名字");
        keynote1.put("color", "#000000");
        Map<String, Object> keynote2 = new HashMap<String, Object>();
        keynote2.put("value", "事假");
        keynote2.put("color", "#000000");
        Map<String, Object> keynote3 = new HashMap<String, Object>();
        keynote3.put("value", "2025-7-8");
        keynote3.put("color", "#000000");
        Map<String, Object> remark = new HashMap<String, Object>();
        remark.put("value", "beizhu");
        remark.put("color", "#000000");
        data_map.put("first", first);
        data_map.put("keyword1", keynote1);
        data_map.put("keyword2", keynote2);
        data_map.put("keyword3", keynote3);
        data_map.put("remark", remark);
        map.put("data", data_map);
//            JSONObject json = JSONObject.fromObject(map);
        String json = JSONObject.toJSONString(map);
//            String result = HttpUtil.sendPost(url, json.toString());
        JsonNode ret = null;
        ret = Unirest.post(url).body(json).asJson().getBody();
        System.out.println(ret);
    }

}


//}
